<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="老人姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入老人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
        <el-form-item label="床位号" prop="bedNo">
        <el-input
          v-model="queryParams.bedNo"
          placeholder="请输入床位号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button
          type="primary"
          icon="Plus"
      @click="handleAdd"
          v-hasPermi="['system:recharge:add']"
          style="float: right;"
        >充值</el-button>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:recharge:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:recharge:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:recharge:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    
    <el-table v-loading="loading" :data="rechargeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="充值单号" align="center" prop="rechargeNo" />
       <el-table-column label="老人姓名" align="center" prop="elderly.name" />
       <el-table-column label="床位号" align="center" prop="bed.bedNo" />
      <el-table-column label="充值金额" align="center" prop="rechargeAmount" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod">
        <template #default="scope">
          <dict-tag :options="recharge_method" :value="scope.row.paymentMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="充值凭证图片" align="center" prop="rechargeVoucher" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.rechargeVoucher" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作人" align="center" prop="sysUser.nickName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:recharge:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:recharge:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 充值对话框 -->
    <el-dialog :title="form.id ? '修改充值记录' : '新增充值记录'" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="老人姓名" prop="elderlyId" required>
          <el-select v-model="form.elderlyId" placeholder="请选择老人姓名">
            <el-option
              v-for="elderly in elderlyList"
              :key="elderly.id"
              :label="elderly.name"
              :value="elderly.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值方式" prop="paymentMethod" required>
          <el-select v-model="form.paymentMethod" placeholder="请选择充值方式">
            <el-option
              v-for="dict in recharge_method"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="充值金额" prop="rechargeAmount" required>
          <el-input-number 
            v-model="form.rechargeAmount" 
            :precision="2" 
            :min="0" 
            :step="0.01" 
            placeholder="0.00"
          />
        </el-form-item>
        <el-form-item label="充值凭证" prop="rechargeVoucher" required>
          <image-upload v-model="form.rechargeVoucher"/>
          <div style="margin-top: 5px; color: #909399; font-size: 12px;">
            图片大小不超过2M<br/>
            仅支持上传PNG JPG JPEG类型图片
          </div>
        </el-form-item>
        <el-form-item label="充值备注" prop="remark" required>
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            placeholder="请输入" 
            maxlength="50" 
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Recharge">
import { listRecharge, getRecharge, delRecharge, addRecharge, updateRecharge } from "@/api/system/recharge"
import { listElderly } from "@/api/system/elderly"
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()
const { recharge_method } = proxy.useDict('recharge_method')

const rechargeList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const elderlyList = ref([])
const formRef = ref(null)

const form = reactive({
  id: null,
  elderlyId: null,
  paymentMethod: null,
  rechargeAmount: 0,
  rechargeVoucher: null,
  remark: '',
  rechargeNo: null,
  operator: 1,
  createTime: null,
  updateTime: null,
  isDeleted: 0
})

const rules = reactive({
  elderlyId: [
    { required: true, message: "老人姓名不能为空", trigger: "change" }
  ],
  paymentMethod: [
    { required: true, message: "充值方式不能为空", trigger: "change" }
  ],
  rechargeAmount: [
    { required: true, message: "充值金额不能为空", trigger: "blur" },
    { type: 'number', min: 0, message: '充值金额必须大于0', trigger: 'blur' }
  ],
  rechargeVoucher: [
    { required: true, message: "充值凭证不能为空", trigger: "change" }
  ],
  remark: [
    { required: true, message: "充值备注不能为空", trigger: "blur" },
    { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
  ]
})

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: null,
  bedNo: null
})

// 获取老人列表
function getElderlyList() {
  listElderly({ pageNum: 1, pageSize: 1000 }).then(response => {
    elderlyList.value = response.rows || []
  }).catch(error => {
    console.error('获取老人列表失败:', error)
    elderlyList.value = []
  })
}

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 提取床位信息
function extractBedInfo(elderlyData) {
  if (elderlyData.bedId) {
    return elderlyData.bedId
  }
  if (elderlyData.bed && elderlyData.bed.id) {
    return elderlyData.bed.id
  }
  return null
}
  
/** 查询预缴款充值列表 */
function getList() {
    loading.value = true
  listRecharge(queryParams).then(response => {
    rechargeList.value = response.rows || []
      total.value = response.total || 0
      loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  getElderlyList()
  open.value = true
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  getElderlyList()
  
  const _id = row.id
  getRecharge(_id).then(response => {
    Object.assign(form, response.data || response)
    open.value = true
  }).catch(error => {
    console.error('获取详情失败:', error)
    proxy.$modal.msgError('获取详情失败，请重试')
  })
}

// 表单重置
function reset() {
  Object.assign(form, {
    id: null,
    elderlyId: null,
    paymentMethod: null,
    rechargeAmount: 0,
    rechargeVoucher: null,
    remark: '',
    rechargeNo: null,
    operator: 1,
    createTime: null,
    updateTime: null,
    isDeleted: 0
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

/** 提交按钮 */
function submitForm() {
  if (!form.elderlyId) {
    proxy.$modal.msgError('请选择老人姓名')
    return
  }
  
  if (!form.paymentMethod) {
    proxy.$modal.msgError('请选择充值方式')
    return
  }
  
  if (!form.rechargeAmount || form.rechargeAmount <= 0) {
    proxy.$modal.msgError('请输入有效的充值金额')
    return
  }
  
  if (!form.rechargeVoucher) {
    proxy.$modal.msgError('请上传充值凭证')
    return
  }
  
  if (!form.remark || form.remark.trim() === '') {
    proxy.$modal.msgError('请填写充值备注')
    return
    }
    
    // 准备提交数据
  const submitData = { ...form }
  
  // 处理床位信息
  if (submitData.elderlyId && elderlyList.value.length > 0) {
    const selectedElderly = elderlyList.value.find(elderly => elderly.id === submitData.elderlyId)
    if (selectedElderly) {
      const bedId = extractBedInfo(selectedElderly)
      if (bedId) {
        submitData.extraField1 = bedId
      }
    }
  }
  
  // 生成充值单号
  if (!submitData.id) {
    const now = new Date()
    const year = String(now.getFullYear()).slice(2)
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    const randomNum = String(Math.floor(Math.random() * 1000)).padStart(3, '0')
    
    submitData.rechargeNo = `PR${year}${month}${day}${hours}${minutes}${seconds}${randomNum}`
    submitData.createTime = formatDate(now)
  } else {
    submitData.updateTime = formatDate(new Date())
  }
  
  // 提交数据
    if (submitData.id != null) {
      updateRecharge(submitData).then(response => {
        proxy.$modal.msgSuccess("修改成功")
        open.value = false
        getList()
      }).catch(error => {
      console.error('修改失败:', error)
      proxy.$modal.msgError('修改失败，请重试')
      })
    } else {
      addRecharge(submitData).then(response => {
        proxy.$modal.msgSuccess("新增成功")
        open.value = false
        getList()
      }).catch(error => {
      console.error('新增失败:', error)
      proxy.$modal.msgError('新增失败，请重试')
      })
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除预缴款充值编号为"' + _ids + '"的数据项？').then(function() {
    return delRecharge(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/recharge/export', {
    ...queryParams
  }, `recharge_${new Date().getTime()}.xlsx`)
}

getList()
</script>